package com.uoko.fileupload.util;

import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.InputStream;
import java.security.MessageDigest;

/**
 * <p>
 * 创建MD5
 * </p>
 *
 * @author shaohua
 * Email shaohua@uoko.com
 * created by 2018/6/8
 */
public class CreateMd5 {

    /**
     * 根据文件流获取md5
     *
     * @param file
     * @return
     * @throws Exception
     */
    public static StringBuilder createMd5(@NotNull final MultipartFile file)
            throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        //生成MD5实例
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        InputStream inputStream = file.getInputStream();
        int available = inputStream.available();
        byte[] bytes = new byte[available];
        md5.update(bytes);
        for (byte b : bytes) {
            //将生成的字节MD5值转换成字符串
            stringBuilder.append(String.format("%02X", b));
        }
        return stringBuilder;
    }

}
